### PACKAGE PREAMBLE ###

# Create a vector of package names
packages <- c("dplyr", "ggplot2", "tidyr", "tidyverse", "data.table", "readxl", "foreign", "devtools", "fixest", "sandwich", "modelsummary", "kableExtra")

installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}

# Packages loading
invisible(lapply(packages, library, character.only = TRUE))
rm(packages, installed_packages)

options(modelsummary_format_numeric_latex = "plain")
f <- function(x) format(x, digits = 3, nsmall = 2, scientific = FALSE)

getwd()
setwd(dir = "/Users/jmc4qg/The Lab Dropbox/Jonathan Colmer/ShotSpotter_env/Journal_submissions/ReStat/Replication Folder/")
mydata <- read.dta("Analysis Data/NIBRS_analysis.dta")

# Panel A: Morning

T1_M <- feols(homicide_pc_morning~ tMean + prec , data=mydata)
summary(T1_M, cluster="fips")
T2_M <- feols(homicide_pc_morning~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_M, cluster="fips")
T3_M <- feols(homicide_pc_morning~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_M, cluster="fips")
T4_M <- feols(homicide_pc_morning~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_M, cluster="fips")

models <- list(T1_M, T2_M, T3_M, T4_M)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_C4/Table_C4_Panel_A.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel B: Afternoon

T1_A <- feols(homicide_pc_afternoon~ tMean + prec , data=mydata)
summary(T1_A)
T2_A <- feols(homicide_pc_afternoon~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_A, cluster="fips")
T3_A <- feols(homicide_pc_afternoon~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_A, cluster="fips")
T4_A <- feols(homicide_pc_afternoon~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_A, cluster="fips")

models <- list(T1_A, T2_A, T3_A, T4_A)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_C4/Table_C4_Panel_B.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel C: Night

T1_N <- feols(homicide_pc_night~ tMean + prec , data=mydata)
summary(T1_N)
T2_N <- feols(homicide_pc_night~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_N, cluster="fips")
T3_N <- feols(homicide_pc_night~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_N, cluster="fips")
T4_N <- feols(homicide_pc_night~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_N, cluster="fips")

models <- list(T1_N, T2_N, T3_N, T4_N)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_C4/Table_C4_Panel_C.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))
